package com.hliushi.netty.c3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author llhuang10
 * @date 2021/10/19 10:24
 */
@Slf4j
public class EventLoopServer {

    public static void main(String[] args) {
        // 细节2: 创建一个独立的EventLoopGroup()
        DefaultEventLoopGroup normalWorkers = new DefaultEventLoopGroup(2);

        new ServerBootstrap()
                // boss 和 worker
                // 细节1: boss 只负责 ServerSocketChannel上accept事件    worker只负责socketChannel上的读写
                .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // netty自带的日志打印
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(normalWorkers, "myHandler", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = msg instanceof ByteBuf ? (ByteBuf) msg : null;
                                if (buf != null) {
                                    byte[] bufByte = new byte[16];
                                    ByteBuf len = buf.readBytes(bufByte, 0, buf.readableBytes());
                                    log.debug(new String(bufByte));
                                }
                            }
                        });
                    }
                })
                .bind(10010);
    }
}
